package com.nova.bluetooth.service;
import android.app.Service;
import android.content.Intent;
import android.media.session.MediaSession;
import android.os.IBinder;
import android.view.KeyEvent;

import com.nova.bluetooth.helpUtils.ToastUtils;

public class MediaPlaybackService extends Service {
    private MediaSession mediaSession;

    @Override
    public void onCreate() {
        super.onCreate();
        mediaSession = new MediaSession(this, "MediaPlaybackService");
        mediaSession.setCallback(new MediaSessionCallback());
        mediaSession.setActive(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaSession.release();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MediaSessionCallback extends MediaSession.Callback {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
            KeyEvent keyEvent = mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            if (keyEvent != null) {
                int action = keyEvent.getAction();
                int keyCode = keyEvent.getKeyCode();
                if (action == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_MEDIA_PLAY:
                        case KeyEvent.KEYCODE_MEDIA_PAUSE:
                        case KeyEvent.KEYCODE_MEDIA_NEXT:
                        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                            // 处理按键事件
                            wakeUpApp();
                            return true;
                    }
                }
            }
            return super.onMediaButtonEvent(mediaButtonEvent);
        }
    }

    private void wakeUpApp() {
        ToastUtils.show("接收到到按键功能广播");
//        Intent launchIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//        if (launchIntent != null) {
//            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(launchIntent);
//        }
    }
}
